package com.bwie.web.controller;

import com.bwie.pojo.Order;
import com.bwie.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
public class OrderController {

    //注入RestTemplate
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/{id}")
    public Order listById(@PathVariable String id){

        //模拟从数据库查询出的数据
        Order order= new Order(id,"小米手机"+id,id,null);
        //远程请求用户微服务，根据id查询用于信息
//        User user = restTemplate.getForObject("http://localhost:9001/user/" + id, User.class);
        //从Eureka中获取实例来调用
        //要调用的服务名                                   在配置文件中显示为配置规则
        User user = restTemplate.getForObject("http://springclouddemo-user/user/" + id, User.class);


        //取值赋值
        order.setUserName(user.getUsername());

        return order;
    }

    //扩展
    @GetMapping("/aa/{id}")
    public ResponseEntity<Order> listById2(@PathVariable String id){

        //模拟从数据库查询出的数据
        Order order= new Order(id,"小米手机"+id,id,null);
        //远程请求用户微服务，根据id查询用于信息
//        User user = restTemplate.getForObject("http://localhost:9001/user/" + id, User.class);
//        ResponseEntity<User> userResponseEntity = restTemplate.getForEntity("http://localhost:9001/user/" + id, User.class);

        //从Eureka中获取实例来调用
        ResponseEntity<User> userResponseEntity = restTemplate.getForEntity("http://springclouddemo-user/user/" + id, User.class);

//        获取实例的状态码
        int statusCodeValue = userResponseEntity.getStatusCodeValue();
        System.out.println("状态码："+statusCodeValue);
//        HttpHeaders headers = userResponseEntity.getHeaders();

        User user = userResponseEntity.getBody();
        //取值赋值
        order.setUserName(user.getUsername());
        //响应结果
        ResponseEntity<Order> orderResponseEntity = ResponseEntity.ok(order);

        return orderResponseEntity;
    }
}
